public class HashBuck {

    public static class Node{
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array = new Node[10];
    public int usedSize;
    public static final float LOAD_FACTOR = 0.75f;

    public void put(int key,int val){

        //首先通过哈希函数找到key的位置
        int index = key % array.length;

        //判断当前数组下标的链表中有没有key值，如果有，则更新其val值
        Node cur = array[index];
        while(cur != null){
            if(cur.key == key){
                cur.val = val;
            }
            cur = cur.next;
        }

        //若没有key值，则进行尾插法(JDK8之后是尾插法，之前是前插法)
        Node node = new Node(key, val);
        node.next = array[index];
        array[index] = node;
        usedSize++;

        //计算负载因子，若 >= 0.75 则进行扩容
        if(getLoadFactor() >= LOAD_FACTOR){
            resizeHash();
        }
    }

    //扩容(再次哈希)
    private void resizeHash() {
        Node[] newArray = new Node[array.length*2];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while(cur != null){
                int newIndex = cur.key % newArray.length;
                Node curN = cur.next;
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = curN;
            }
        }
        array = newArray;
    }

    private float getLoadFactor() {
        return usedSize*1.0f / array.length;
    }

    //查找
    public int get(int key){
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null){
            if(cur.key == key){
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
